/*
 * Copyright 2011 ArcBees Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.arcbees.server.auth;

import javax.inject.Named;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Provider;

/**
 * @author Christian Goudreau
 */
public class CookieUtilitiesImpl implements CookieUtilities {
  private final Integer cookieTimeout;
  private final String sessionIdName;
  private final Provider<HttpServletRequest> httpServletRequestProvider;
  private final Provider<HttpServletResponse> httpServletResponseProvider;

  @Inject
  public CookieUtilitiesImpl(
      final Provider<HttpServletRequest> httpServletRequestProvider,
      final Provider<HttpServletResponse> httpServletResponseProvider,
      @Named("COOKIE_TIMEOUT") final Long cookieTimeOut,
      @Named("SESSION_ID_NAME") final String sessionIdName) {

    this.httpServletRequestProvider = httpServletRequestProvider;
    this.httpServletResponseProvider = httpServletResponseProvider;
    this.sessionIdName = sessionIdName;
    this.cookieTimeout = cookieTimeOut.intValue() / 1000;
  }

  @Override
  public Cookie getSessionCookie() {
    HttpServletRequest request = httpServletRequestProvider.get();

    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(sessionIdName)) {
          return cookie;
        }
      }
    }

    return null;
  }

  @Override
  public void createSessionCookie(UserSession userSession) {
    HttpServletResponse response = httpServletResponseProvider.get();

    Cookie cookie = new Cookie(sessionIdName, userSession.getCookie());
    cookie.setMaxAge(cookieTimeout);

    response.addCookie(cookie);
  }
}
